package com.fzg.common.tool;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Base64;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * create by fzg
 * 2021/10/12 9:41
 */


public class JwtUtil {

    private static final String TOKEN = "token!Q@W3e4r";

    /*** 生成token * @param map //传入payload * @return 返回token */
    public static String getToken(Map<String,String> map){
        JWTCreator.Builder builder = JWT.create();
        map.forEach(builder::withClaim);
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR,24*3);
        builder.withExpiresAt(instance.getTime());
        return builder.sign(Algorithm.HMAC256(TOKEN));
    }

    /**
     * 整合springboot
     * 验证token
     * @param token 参数：token
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }


    /*** 获取token中payload * @param token * @return */
    public static DecodedJWT getToken(String token){
        return JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }

    // token 获取id
    public static Integer getTokenId(String token){
        DecodedJWT untoken = JwtUtil.getToken(token);
        String payload = untoken.getPayload();
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] bytes = decoder.decode(payload);
        //System.out.println("BASE64解密：" + new String(bytes));
        String str = new String(bytes);
        HashMap hashMap = JSON.parseObject(str, HashMap.class);
        Integer aid = Integer.parseInt(hashMap.get("aid").toString());
        return aid;
    }

    // 解密token
    public static String getClaim(String token, String key) {
        DecodedJWT decodedJWT = JWT.decode(token);
        Claim value = decodedJWT.getClaim(key);
        return value.asString();
    }

}
